/**
 * 
 */
package com.lemote.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author wuhui
 * 
 *         下午03:06:57
 */
public class CodeUtils {
	private static String BIG_LETTER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	private static String LOWER_LETTER = "abcdefghijkmnopqrstuvwxyz";
	private static String NUMBER = "0123456789";
	
	/**
	 * 
	 * @param big 是否有包括大写字母
	 * @param lower 是否有包括小写字母
	 * @param number 是否有包括数字
	 * @return
	 */
	public static Map<String, Object> makeCode(Boolean big,Boolean lower,Boolean number){
		
		return makeCode(50, 20, big, lower, number);
	}
	
	/**
	 * 生成验证码，包含大写字母，小写字母
	 * @return
	 */
	public static Map<String, Object> makeCode(){
		
		return makeCode(50, 20, true, true, false);
	}
	/**
	 * 生成验证码
	 * @param width 50 
	 * @param height 20 
	 * @param big 是否有包括大写字母
	 * @param lower 是否有包括小写字母
	 * @param number 是否有包括数字
	 * @return map 中code:验证码值 image:图片对象
	 */
	public static Map<String, Object> makeCode(Integer width,Integer height,Boolean big,Boolean lower,Boolean number) {
		Map<String, Object> codes = new HashMap<String, Object>();
		BufferedImage img = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		StringBuffer sb = new StringBuffer();
		char[] ch = makeCharacter(big, lower, number);
		String value = null; 
		// 得到该图片的绘图对象
		Graphics g = img.getGraphics();
		Random r = new Random();
		Color c = new Color(200, 150, 255);
		g.setColor(c);
		// 填充整个图片的颜色
		g.fillRect(0, 0, width, height);
		// 向图片中输出数字和字母
		int index, len = ch.length;
		for (int i = 0; i < 4; i++) {
			AffineTransform fontAT = new AffineTransform();
			int rotate = r.nextInt(25);
			fontAT.rotate(r.nextBoolean() ? Math.toRadians(rotate) : -Math
					.toRadians(rotate / 2));
			index = r.nextInt(len);
			g.setColor(new Color(r.nextInt(88), r.nextInt(188), r
							.nextInt(255)));
			Font fx = new Font(new String[] { "Times New Roman", "Verdana",
					"Arial" }[r.nextInt(2)],Font.BOLD | Font.ITALIC, 13 + r.nextInt(3))
					.deriveFont(fontAT);
			g.setFont(fx);// 输出的字体和大小
			g.drawString("" + ch[index], (i * 11) + 3, r.nextInt(8) + 11);// 写什么数字，在图片的什么位置画
			sb.append(ch[index]);
		}
		g.dispose();
		codes.put("code", sb.toString());
		codes.put("image", img);
		return codes;
	}

	/**
	 * @param big
	 * @param lower
	 * @param number
	 * @param sb
	 */
	private static char[] makeCharacter(Boolean big, Boolean lower,
			Boolean number) {
		StringBuffer sb = new StringBuffer();
		if (big) {
			sb.append(BIG_LETTER);
		}
		if (lower) {
			sb.append(LOWER_LETTER);
		}
		if (number) {
			sb.append(NUMBER);
		}
		return sb.toString().toCharArray();
	}
	
}
